layui.define(['layer', 'form'], function (exports) {
    var $ = layui.$
    var form = layui.form
    var layer = layui.layer

    var tongYong = {
        tongYong1: function () {
            var savedFormData = [];
            // var taskID = null
            // alert("加载了")
            var storage = window.localStorage;
            var click_store = null
            let groups_check = {}
            //获取配置缓存
            let htmlName = window.document.location.pathname.replace(".html", "").replace("/page/task/", "")
            let optionData = storage.getItem(htmlName)
            // console.log(optionData);
            //设置配置缓存
            if (optionData && optionData != "") {
                // console.log(optionData);
                optionData = JSON.parse(optionData)
                for (let key in optionData) {
                    try {
                        if (optionData[key] && optionData[key] != "") {
                            let temDom = document.getElementsByName(key)[0]
                            // console.log(temDom);
                            if (temDom.type == "number" || temDom.type == "text" || temDom.type == "textarea") {
                                temDom.value = optionData[key]
                            } else if (temDom.type == "radio") {
                                let idid = optionData[key]
                                if (/^\d+$/.test(idid)) {
                                    idid = "数字" + idid
                                }
                                document.getElementById(idid).checked = "on"
                                form.render("radio");
                            } else if (temDom.type == "checkbox") {
                                temDom.checked = "on"
                            } else {
                                console.log("未知dom类型:" + temDom.type);
                            }
                        }
                    } catch (error) {
                        console.log(error)
                        // console.log("-----------------")
                    }
                }

            }

            let groupData = storage.getItem("groupData")
            // console.log("groupData" + groupData);
            if (!groupData || groupData == "") {
                $.get("/indexGroup", function (res, status) {
                    if (status) {
                        // console.log("任务分组初始化成功")
                        groupData = (res.data)
                        storage.setItem("groupData", JSON.stringify(groupData))
                        groupData.forEach(groupDoc => {
                            // console.log("groupDoc",groupDoc);
                            addInput(groupDoc)
                        })
                        addInput({ _id: '空闲', groupName: '空闲列表' })
                        addInput({ _id: '忙碌', groupName: '忙碌列表' })
                        addInput({ _id: '全部', groupName: '全部列表' })
                        form.render("checkbox");
                    } else {
                        layer.msg("访问服务器失败")
                    }
                })
            } else {
                groupData = JSON.parse(groupData)
                groupData.forEach(groupDoc => {
                    // console.log("groupDoc",groupDoc);
                    addInput(groupDoc)
                })
                addInput({ _id: '空闲', groupName: '空闲列表' })
                addInput({ _id: '忙碌', groupName: '忙碌列表' })
                addInput({ _id: '全部', groupName: '全部列表' })
                form.render("checkbox");
            }

            //监听storage事件
            window.addEventListener("storage", function (e) {
                window.location.reload();
                // console.log("监听到storage事件并刷新");
                // layer.msg("刷新")
            });
            // form.on('submit(bcgjc)', function (data) {
         
            //     console.log("data");
                
            //     return false;
            // });

            //监听提交任务
            form.on('submit(tijiao)', function (data) {
                btn_renWu(data)
                return false;
            });

            // //监听提交任务组
            // form.on('submit(tijiaoTasks)', function (data) {
            //     //拿出设备列表(通过data拿到) 拿出任务组列表
            //     // alert(`提交>>>${JSON.stringify(savedFormData)}`)
            //     btn_renWu(data, "多任务", savedFormData)
            //     return false;
            // });


            form.on('submit(saveTask)', function (data) {

                let newTask = data.field
                // 删除特定的键
                for (let key in newTask) {
                    if (newTask[key].includes("◉")) {
                        delete newTask[key];
                    }
                }

                savedFormData.push(newTask)

                let formattedData = savedFormData.map(function (item) {
                    return JSON.stringify(item, null, 2); // 格式化对象，使其更易于阅读
                });

                $('#zhuiJia').html(formattedData.join("<br>"));

                return false;
            });

            form.on('submit(delTask)', function (data) {
                $('#zhuiJia').html("无任务组");
                savedFormData = []
                return false;
            });


            //监听全选
            form.on('checkbox(quanXuan1)', function (data) {
                if (data.elem.checked) {
                    // $("#groups1").children().prop("class", "layui-btn")
                    groupData.forEach(groupDoc => {
                        let dom = $('input[name="' + groupDoc.groupName + '"]')
                        dom.attr("class", "layui-btn")
                        // dom.attr("value", "✓" + group.groupName)
                        groups_check[groupDoc.groupName] = groupDoc._id
                    })
                    $("#inputaaa").attr("value", JSON.stringify(groups_check))
                } else {
                    $("#groups1").children().prop("class", "layui-btn layui-btn-primary")
                    groups_check = {}
                    $("#inputaaa").attr("value", "")
                }
                form.render("checkbox");
            })


            // // 监听窗口关闭事件，当窗口关闭时，
            // window.onbeforeunload = function () {
            //     ws.close();
            // }

            function btn_renWu(data, type, savedFormData) {
                let taskName = data.elem.value
                //汇总所有设备
                let groupDocArr = []
                let socketIdArr = []
                //groups_check = {"分组1":["root_a111"],"分组2":"7574546546","分组3":null}
                for (let groupName in groups_check) {
                    let groupValue = groups_check[groupName]
                    if (groupValue) {
                        if (typeof (groupValue) == "string") {
                            // console.log("是字符串:" + groupValue);
                            groupDocArr.push({ groupName: groupName, groupId: groupValue })
                        } else {//是数组
                            for (let i in groupValue) {
                                if (!socketIdArr.includes(groupValue[i])) {
                                    socketIdArr.push(groupValue[i])
                                }
                            }
                        }
                    }
                }

                if (groupDocArr.length == 0 && socketIdArr.length == 0) {
                    layer.msg("没选择任何设备")
                    return false
                }


                // console.log("groupDocArr", groupDocArr);

                let taskData = data.field
                for (let oneData in taskData) {
                    if (taskData[oneData].indexOf("◉") > -1) {
                        delete taskData[oneData];
                    }
                }

                storage.setItem(htmlName, JSON.stringify(taskData))




                layer.confirm(`执行[${taskName}]的任务??`, function (index) {
                    layer.close(index);

                    // if (type == "多任务") {
                    //     taskName = `${taskName}_多任务`
                    //     // taskData = savedFormData
                    //     taskData = { 任务组: savedFormData }
                    //     // $.post('/tasks_arr/setTaskArr', { taskName: taskName, taskArr: savedFormData }, function (resdata) {
                    //     //     layer.msg(resdata.msg)
                    //     // })
                    //     let msg = "保存多任务失败"
                    //     $.ajax({
                    //         type: 'POST',
                    //         url: '/tasks_arr/setTaskArr',
                    //         data: { taskName: taskName, taskArr: savedFormData },
                    //         async: false,  // 设置为 false 以使请求同步
                    //         success: function (resdata) {
                    //             // layer.msg(resdata.msg);
                    //             console.log(resdata.msg);
                    //             msg = resdata.msg
                    //             taskData.taskID = resdata.taskID
                    //         },
                    //         error: function (xhr, status, error) {
                    //             // 错误处理
                    //             console.error("Error: " + error);
                    //             msg = error.message
                    //         }
                    //     });

                    //     if (!taskData.taskID) {
                    //         console.log(msg)
                    //         layer.msg(msg)
                    //         return
                    //     }
                    // }

                    if (taskName == "作品关注" || taskName == "作品点赞" || taskName == "主页关注" || taskName == "一键进入直播间") {
                        let uid = getUid(taskData.链接)
                        if (!uid) {
                            layer.msg("解析uid失败")
                            return
                        }
                        // console.log("uid", uid);
                        taskData.uid = uid
                    }

                    let newData = {
                        groupDocArr: groupDocArr, socketIdArr: socketIdArr, taskName: taskName, timeStamp: Date.now(), taskData: taskData, userName: storage.getItem("userName")
                    }
                    axios.post('/wsRouter/faTast', { type: "任务", data: newData }).then(res => {
                        layer.msg(res.data.msg)
                    }).catch(e => {
                        layer.alert(e.message)
                    })
                });

            }

            function addInput(groupDoc) {
                let button = document.createElement('input')
                button.type = "button"
                button.value = "◉" + groupDoc.groupName
                button.name = groupDoc.groupName
                button.className = "layui-btn layui-btn-primary"
                if (groupDoc.groupName == "空闲列表") {
                    button.style.color = "#00CCFF"; // 设置按钮名称的颜色为红色
                } else if (groupDoc.groupName == "忙碌列表") {
                    button.style.color = "#FFCC00"; // 设置按钮名称的颜色为黄色
                } else if (groupDoc.groupName == "全部列表") {
                    button.style.color = "#F00"; // 设置按钮名称的颜色为红色
                }
                button.onclick = function () {//单击
                    if (this.name == "空闲列表" || this.name == "忙碌列表" || this.name == "全部列表") {
                        layer.msg("空闲/忙碌/全部列表不支持全选,请双击进入")
                        return
                    }
                    if (click_store != null) {
                        clearTimeout(click_store);
                        click_store = null
                    }
                    click_store = setTimeout(function () {
                        let dom = $('input[name="' + groupDoc.groupName + '"]')
                        let domClass = dom.attr("class")
                        if (domClass == "layui-btn") {
                            dom.attr("class", "layui-btn layui-btn-primary")
                            groups_check[groupDoc.groupName] = null
                            $("#inputaaa").attr("value", JSON.stringify(groups_check))
                        } else if (domClass == "layui-btn layui-btn-primary") {
                            dom.attr("class", "layui-btn")
                            groups_check[groupDoc.groupName] = groupDoc._id
                            $("#inputaaa").attr("value", JSON.stringify(groups_check))
                        }
                    }, 300)
                };
                button.ondblclick = function () {//双击
                    if (click_store != null) {
                        clearTimeout(click_store);
                        click_store = null
                    }
                    let dom = $('input[name="' + groupDoc.groupName + '"]')
                    let domClass = dom.attr("class")
                    if (domClass == "layui-btn layui-btn-warm") {
                        groups_check[groupDoc.groupName] = null
                        $("#inputaaa").attr("value", JSON.stringify(groups_check))
                        dom.attr("class", "layui-btn layui-btn-primary")
                    } else if (domClass == "layui-btn layui-btn-primary") {
                        //展开分组下的设备列表
                        window.groupObj = {
                            groupName: groupDoc.groupName,
                            _id: groupDoc._id
                        }
                        // console.log(group._id);
                        layer.open({
                            title: '【' + groupDoc.groupName + '】下面的设备列表',
                            type: 2,
                            area: ['80%', '98%'],
                            content: '/page/devices/tableGroup_deviceList.html',
                            closeBtn: 1,
                            shadeClose: true,//其他区域关闭
                            btn: ['确认', '取消'],
                            yes: function (index, layero) {
                                let iframeWin = $(layero).find('iframe')[0].contentWindow
                                let socketIdArr = iframeWin.formData()
                                if (socketIdArr) {
                                    dom.attr("class", "layui-btn layui-btn-warm")
                                    groups_check[groupDoc.groupName] = socketIdArr
                                    $("#inputaaa").attr("value", JSON.stringify(groups_check))
                                    layer.close(index);
                                }

                            },
                            // btn2: function () {//取消

                            // }
                        });
                    }
                };
                document.getElementById("groups1").appendChild(button)
            }

            function getUid(url) {
                // console.log(111);
                //解析主页uid
                let uid = null
                url = url.match(/https:\/\/v\.douyin\.com\/[\d\w\/]+/)[0]
                // console.log("url", url);
                $.ajax({
                    url: "/toUrl?url=" + url,
                    type: "GET", //请求方式为get
                    //contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                    async: false,
                    dataType: "json", //返回数据格式为json
                    success: function (res) { //请求成功完成后要执行的方法 
                        console.log(res.msg);
                        if (res.code == 1) {
                            uid = res.uid.replace("/", "")
                            console.log("uid:" + uid)
                            // callback(uid)
                        } else {
                            layer.msg(res.msg)
                        }
                    },
                    error: function (xhr, textstatus, thrown) {
                        layer.msg('解析url接口有误');
                    }
                })
                // if (uid) {
                return uid
                // }
            }
        },
    };
    exports('tongYong', tongYong);
});
